package top.cross.webapp.common.webview;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import top.cross.webapp.common.R;
import top.cross.webapp.common.base.BaseStatusBarActivity;
import top.cross.webapp.common.mutilweb.WebViewStartUtil;
import top.cross.webapp.common.plugin.TestPlugin;
import top.crossrun.webview.bridge.core.pls.BridgeCallBackFunction;
import top.crossrun.webview.bridge.core.utils.BridgeHelper;
import top.crossrun.webview.bridge.core.utils.BridgeUtil;
import top.crossrun.webview.bridge.core.utils.RawJSEval;
import top.crossrun.webview.bridge.webview.SysWebView.SysWebViewChromeClient;
import top.crossrun.webview.bridge.webview.SysWebView.SysWebViewHelper;


/**
 * H5页面展示界面 需要传入标题和url
 */

public class WebViewActivity extends BaseStatusBarActivity {

    private WebView webView;

    private String url;

    private BridgeHelper bridgeHelper;

    private SysWebViewChromeClient sysWebViewChromeClient;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

//        url = getIntent().getStringExtra("url");
        url = "http://192.168.222.173:8080/gdcla/test.html";
        url = "https://mo.baidu.com/mo/home";
        if (TextUtils.isEmpty(url)) {
            finish();
            return;
        }
        initWebView();
        webView.loadUrl(url);
    }

    /**
     * 获取展示内容布局ID R.layout.xxx
     *
     * @return
     */
    @Override
    public int getLayoutRes() {
        return R.layout.activity_oa_webview;
    }

    /**
     * 初始化标题栏相关操作
     */
    @Override
    public void initTitleLayout() {
        setTitleVisibility(false);
    }

    /**
     * 获取传入的Intent数据
     */
    @Override
    public void initIntentData() {

    }

    /**
     * 初始化界面组件
     */
    @Override
    public void initView() {
        webView = findViewById(R.id.webView);
        findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                webView.reload();
                JSONObject obj = new JSONObject();
                try {
                    obj.put("a", 116.40769);
                    obj.put("b", 39.89945);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                webView.reload();
            }
        });
//        {"handlerName":"test","data":{"params":{"dd":"dd"}},"callbackId":"cb_1_1593420555414"}
        findViewById(R.id.tohtml).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bridgeHelper.callHandler("tohtml"
                        , ""
                        , new BridgeCallBackFunction() {
                            @Override
                            public void onCallBackFunction(String msg) {
                                Log.e("console", "Android | callHandler = " + BridgeUtil.decode(msg));
                            }
                        });
            }
        });
    }

    private void initWebView() {

//        bridgePluginInterfaceAdapter = new WebViewBridgePluginManagerAdapter(new RawJSEval(webView)) {
//            @Override
//            public Activity getActivityContext() {
//                return WebViewActivity.this;
//            }
//
//            @Override
//            public String getBridgeJS() {
////                return BridgeUtil.assetFile2Str(WebViewActivity.this, "b.js");
//                return BJS.js;
//            }
//        };
//
//        bridgeHelper = new BridgeHelper(bridgePluginInterfaceAdapter);
//        bridgeHelper.setkCustomProtocolScheme();
//        bridgeHelper.setkCustomreturnHost();
//        bridgeHelper.setkQueueHasMessage();

//        bridgeHelper = new BridgeHelper(bridgePluginInterfaceAdapter, new WebViewBridgePlugin() {
//            @Override
//            public void handlerBridgeMsg(String msg, BridgeCallBackFunction callBackFunction) {
//                //没有被其他插件处理的信息
//            }
//        });

        sysWebViewChromeClient = new SysWebViewChromeClient(this, 1, null, null);

        bridgeHelper = new BridgeHelper(this, new RawJSEval(webView));

//        bridgeHelper.registerHandler(new WebViewBridgePluginWithActivityLife("test") {
//            @Override
//            public void handlerBridgeMsg(String msg, BridgeCallBackFunction callBackFunction) {
//                Toast.makeText(WebViewActivity.this, msg, Toast.LENGTH_LONG).show();
//                callBackFunction.onCallBackFunction(Calendar.getInstance().getTime().toString());
//            }
//
//            @Override
//            public void onResume() {
//                super.onResume();
//                Log.e("console","onResume");
//            }
//
//            @Override
//            public void onPause() {
//                super.onPause();
//                Log.e("console","onPause");
//            }
//        });

        bridgeHelper.pluginRegister(new TestPlugin());

        bridgeHelper.pluginRegister("test", TestPlugin.class);

        webView.setWebChromeClient(sysWebViewChromeClient);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("console", "should url =" + url);
                if (bridgeHelper.shouldOverrideUrlLoading(BridgeUtil.decode(url), true)) {
                    return true;
                }
                if (url.startsWith("http") || url.startsWith("https")) {
                    view.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                Log.e("console", "onLoadResource url =" + url);
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                bridgeHelper.onPageFinished(url);
            }
        });

        SysWebViewHelper.initWebView(webView);

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Log.e("console", "onDownloadStart ===");
                Log.e("console", url);
                Log.e("console", userAgent);
                Log.e("console", contentDisposition);
                Log.e("console", mimetype);
                Log.e("console", "onDownloadStart +++");
                Intent ext = new Intent();
                ext.setAction(Intent.ACTION_VIEW);
                ext.addCategory(Intent.CATEGORY_BROWSABLE);
                ext.setData(Uri.parse(url));
                if (BridgeUtil.isIntentAvailable(WebViewActivity.this, ext)) {
                    startActivity(ext);
                }
//                ext.setType(mimetype);
//                startActivity(ext);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();
                return false;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration config) {
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
        super.onConfigurationChanged(config);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bridgeHelper != null) {
            bridgeHelper.onDestroy();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        bridgeHelper.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        bridgeHelper.onPause();
    }

    public void jump(View view) {
        WebViewStartUtil.start(this, ((Button) view).getText().toString(), ((Button) view).getText().toString());
    }

    private List<String> packageNameList = new ArrayList<String>();

    private List getLauncherPackageName(Intent intent) {
        PackageManager pm = this.getPackageManager();
        //设置指定Intent，当前设置的是符合桌面应用设定的Activity，即：
        // <action android:name="android.intent.action.MAIN" />
        // <category android:name="android.intent.category.LAUNCHER" />
//        Intent intent = new Intent("android.intent.action.MAIN");
//        intent.addCategory("android.intent.category.LAUNCHER");

        //queryIntentActivities()方法检索可以针对给定意图执行的所有活动并返回ResolveInfo。
        //若第二个参数设置为PackageManager.MATCH_DEFAULT_ONLY,则只检索显示添加"android.intent.category.DEFAULT"属性的Activity
        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL);
        for (ResolveInfo info : resolveInfos) {
            String pkgName = info.activityInfo.packageName;
            Log.e("console", "getLauncherPackageName: pkgName = " + pkgName);
        }
        return packageNameList;
    }
}
